<?php
/**
 * Created by PhpStorm.
 * User: dingboxu
 * Date: 17/1/5
 * Time: 上午1:10
 */
namespace Utils;

use Actions\ActionUtils;
use GatewayWorker\Lib\Gateway;

class SysUtils{

    public static $_db;

    /**
     * @param $message
     *
     * 系统日志
     *
     */
    public static function sysLog($message){
        $dateToday = date("Ymd");
        $timeNow = date("Y-m-d H:i:s");
        $ip = $_SERVER["REMOTE_ADDR"];

        $user = "noUser";
        if ($_SESSION[ID]) {
            $user = $_SESSION[ID];
        }

        $log = "[$timeNow] $ip UserId:$user : $message\n";
        file_put_contents(PATH_SYSTEM_LOG_ROOT.$dateToday.".log",$log, FILE_APPEND);
    }


    public static function notifyToOperator(){

    }

    /**
     * @param $userId
     * @param $data
     * @param $event
     * @param $result_code
     * @param $err_msg
     *
     * 推送通讯给前端
     *
     */
    public static function notifyTofFrontEnd($userId,$data,$event,$result_code = RESULT_CODE_OK,$err_msg = null){

        $sendMsg = ActionUtils::getResponseData($data,$event,0,$result_code,$err_msg);
        echo $sendMsg;
        // 发送
        Gateway::sendToUid($userId,$sendMsg);
        //GateWay::sendToAll($sendMsg);
    }





    /**
     * @param $ip_address
     * @param $port
     * @param $hexCommand
     *
     * 向IO卡发送命令
     *
     */
    public static function sendCommandToIoCard($ip_address,$port,$hexCommand){

        $asciiCommand = self::hexCommandToAscii($hexCommand);

        $binStream =  self::Send_socket_xdcoder($port,$ip_address,$asciiCommand);

        $result = bin2hex($binStream);
    }


    /**
     * @param $hexCommand
     * @return string
     *
     * 十六进制命令 转 可发送ascii命令
     *
     */
    public static function hexCommandToAscii($hexCommand){
        $asciiCommand = "";
        for ($i = 0; $i < strlen($hexCommand) - 1; $i+=3) {
            $asciiCommand.=chr(hexdec($hexCommand[$i] . $hexCommand[$i + 1]));
        }
        return $asciiCommand;
    }


    /**
     * @param $bin_str
     * @return string
     *
     * 二进制数据 转 txt
     *
     */
    function bin2text($bin_str)
    {
        $text_str = '';
        $chars = explode("\n",chunk_split(str_replace("\n",'',$bin_str),8));
        $_I = count($chars);
        for($i = 0; $i < $_I; $text_str .= chr(bindec($chars[$i])), $i );
        return $text_str;
    }


    /**
     * @param $service_port
     * @param $address
     * @param $in
     * @return string|void
     *
     * 向服务器和端口号发送报警数据
     *
     */
    public static function Send_socket_xdcoder($service_port, $address, $in) {

        //创建 TCP/IP socket
        $socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP) or die("could not create socket!");
        //设置超时时间
        $timeout = 2;
        $time = time();
        //设置非阻塞模式
        @socket_set_nonblock($socket);
        //超时判断
        while (!@socket_connect($socket, $address, $service_port)) {
            $err = socket_last_error($socket);
            // 连接成功
            if ($err === 10056) {
                break;
            }
            //连接失败，判断超时时间，停止
            if ((time() - $time) >= $timeout) {
                socket_close($socket);
                //echo "网络异常，请检查网络连接！";
                return ;
            }
            // 刷新频率（250毫秒）
            usleep(250000);
        }
        //设置阻塞模式
        @socket_set_block($socket);
        //发送命令到设备
        socket_write($socket, $in, strlen($in));
        //接收设备命令返回数据
        $buffer = socket_read($socket, 1024, PHP_BINARY_READ);
        //sleep(1);
        //关闭连接
        socket_close($socket);
        //输出返回值
        return $buffer;
    }


    public static function query($str)
    {
        if(self::$_db === null) {
            self::$_db = \GatewayWorker\Lib\Db::instance('main');
            return self::$_db->query($str);
        } else {
            return self::$_db->query($str);
        }
    }

    public static function list_paging_util ($table_name,$where,$page_num,$every_page_counts) {

        $list = self::query("select COUNT(*) AS TOTAL_COUNT from $table_name where $where");

        $total_count = 0;
        foreach ($list as $record) {
            $total_count = $record['TOTAL_COUNT'];
        }

        $start = 0;
        if ($page_num > 0) {
            $start = $page_num * $every_page_counts;
        }

        $where .= " LIMIT $start,$every_page_counts";

        $list = self::query("select * from $table_name where $where");

        return array($total_count,$list);

    }

}
